import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//客服端
public class UdpEChoServer {
    private DatagramSocket Server = null;

    public UdpEChoServer() throws SocketException {
        Server = new DatagramSocket();
    }

    public void stack() throws IOException {
        Scanner scanner = new Scanner(System.in);

        while(true) {
            //从控制台读取请求数据
            System.out.print(">:");
            String s = scanner.nextLine();
            DatagramPacket packet = new DatagramPacket(s.getBytes(),s.getBytes().length,
                    //接收方的端口号和IP地址
                    InetAddress.getByName("127.0.1.1"),2000);

            //请求服务器
            Server.send(packet);

            //读取响应数据报
            DatagramPacket packet1 = new DatagramPacket(new byte[4096],4096);
            Server.receive(packet1);

            //把响应的数据包转换成字符串显示
            String s1 = new String(packet1.getData(),0,packet1.getLength());
            System.out.printf("[%s:%d] 请求:%s 响应:%s \n",packet.getAddress(),packet.getPort(),s,s1);

        }
    }

    public static void main(String[] args) throws IOException {
        UdpEChoServer server = new UdpEChoServer();
        server.stack();
    }
}
